'use client'

import { ChatModel } from '@/db/schema'
import { useUser } from '@clerk/nextjs'
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { usePathname, useRouter } from 'next/navigation'
import { Router } from 'next/router'
import React from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query';



type Props = {}

const Navibar = (props: Props) => {
  const queryClient = useQueryClient();

  // 添加删除对话的mutation
  const deleteMutation = useMutation({
    mutationFn: (chatId: number) =>
      axios.post('/api/deleteChat', { chatId }),
    onSuccess: () => {
      // 删除成功后刷新对话列表并跳转
      queryClient.invalidateQueries({ queryKey: ['chats'] });
      router.push('/');
    }
  });

  const { user } = useUser()
  const router = useRouter()

  const { data: chats } = useQuery({
    queryKey: ['chats'],
    queryFn: () => {
      return axios.post('/api/get-chats')
    },
    enabled: !!user?.id
  })

  const pathname = usePathname()


  return (
    <div className='h-screen bg-gray-50 border-r border-gray-200'>
      <div className='flex items-center justify-center p-4 border-b border-gray-200'>
        <p className='font-bold text-2xl text-gray-800'>
          Deepseek
        </p>
      </div>

      <div className='h-12 flex items-center justify-center mt-4 cursor-pointer px-4'
        onClick={() => { router.push('/') }}
      >
        <p className='h-full w-full bg-blue-100 hover:bg-blue-200 rounded-lg flex items-center justify-center font-medium text-blue-700 transition-colors duration-200'>
          创建新会话
        </p>
      </div>

      {/* 对话列表 */}
      <div className='flex flex-col gap-2 p-4 overflow-y-auto h-[calc(100vh-180px)]'>
        {!chats ? (
          // 精确匹配的骨架屏
          Array.from({ length: 5 }).map((_, i) => (
            <div key={i} className={`flex items-center justify-between w-full p-2 rounded-lg border ${i === 0 ? 'bg-blue-50 border-blue-300' : 'border-gray-200'
              }`}>
              <div className="animate-pulse h-4 bg-gray-200 rounded w-[70%]"></div>
              <div className="animate-pulse h-4 w-4 bg-gray-200 rounded-full"></div>
            </div>
          ))
        ) : (
          // 正常渲染的对话列表保持不变
          chats?.data?.map((chat: ChatModel) => (
            <div
              key={chat.id}
              className={`group flex items-center justify-between w-full p-2 rounded-lg border cursor-pointer transition-colors duration-200
                        ${pathname === `/chat/${chat.id}` ?
                  'bg-blue-50 border-blue-300 text-blue-700' :
                  'border-gray-200 hover:bg-gray-100'}`}
            >
              <div
                className="flex-1"
                onClick={() => router.push(`/chat/${chat.id}`)}
              >
                <p className='font-medium text-sm line-clamp-1'>
                  {chat?.title}
                </p>
              </div>
              <button
                className="opacity-0 group-hover:opacity-100 text-red-500 hover:text-red-700 transition-opacity duration-200
                          p-1 rounded-full border border-transparent hover:border-red-300"
                onClick={(e) => {
                  e.stopPropagation();
                  if (confirm('确定要删除这个对话吗？')) {
                    deleteMutation.mutate(chat.id);
                  }
                }}
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
              </button>
            </div>
          ))
        )}
      </div>
    </div>
  )
}

export default Navibar